<template>
  <div>
    <myDivider name="巡查二维码"></myDivider>

    <div>
      <el-input style="width: 250px;margin-left: 10px;" v-model="keywords" placeholder="巡查码名称/类别/扫码权限人"
        @keyup.enter.native="SouSuo" clearable></el-input>
      <el-select @change="SouSuo" clearable v-model="keyResidentialId" placeholder="选择小区">
        <el-option v-for="item, i in keyResidentialData" :key="i" :label="item.name" :value="item.residentialId">
        </el-option>
      </el-select>
      <el-button type="primary" style="margin-top: 20px; margin-left: 15px" @click="SouSuo">查询</el-button>
      <el-button style="margin-top: 20px; margin-left: 15px" @click="reset">重置</el-button>

      <div style="display: flex;justify-content: flex-end;">
        <el-button type="success" @click="exportCode">导出巡查码</el-button>
        <el-button type="danger" plain style="margin-left: 15px" @click="batchDelete">删除</el-button>
      </div>
    </div>

    <div>
      <el-table :data="tableData" ref="table" @select="selectTable" @select-all="selectAllTable"
        style="width: 100%;margin-top: 50px;">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="codeName" label="巡查码名称" align="center">
          <template slot-scope="scope">
            <span style="color:#4095e5; cursor: pointer;" @click="detailClick(scope.row)">{{ scope.row.codeName
              }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="巡查码类别" align="center" width="150">
        </el-table-column>
        <el-table-column prop="" label="巡查码" align="center" width="100">
          <template slot-scope="scope">
            <div>
              <el-popover trigger="hover">
                <img slot="reference" style="width: 50px;height: 50px;" :src="scope.row.codeImageUrl" alt="">
                <div :id="'myNode' + scope.row.id" style="width: 250px;height: 300px;">
                  <img style="width: 150px;height: 150px;display: block;margin: 0 auto;" :src="scope.row.codeImageUrl"
                    alt="">
                  <span style="display: block;margin: 10px 0;font-weight: 600;text-align: center;">{{
                    scope.row.updateTime == 'agency' ? '居委会' : '物业公司' }}--保洁类别</span>
                  <span style="display: block;margin: 10px 0;text-align: center;">{{ scope.row.codeName }}</span>
                  <span style="display: block;margin: 10px 0;text-align: center;">{{ scope.row.residentialInfo }}</span>
                </div>
                <div style="display: flex;justify-content: center;">
                  <el-button type="primary" size="mini" @click="dow(scope.row)">下载</el-button>
                </div>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="categoryResponsibleNames" label="扫码权限人" align="center">
          <template slot-scope="scope">
            <div style="cursor: pointer;">

              <el-popover trigger="hover">
                <span slot="reference">{{
                  scope.row.categoryResponsibleNames.length == 1 ? scope.row.categoryResponsibleNames[0] : scope.row.categoryResponsibleNames[0]+'...'}}</span>
                <div>
                  {{ scope.row.categoryResponsibleNames.join('/') }}
                </div>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="residentialName" label="所属小区" align="center">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.residentialInfo" placement="top-start">
              <span>{{ scope.row.residentialName }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="areaName" label="地址">
            <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.areaName" placement="top-start">
              <span>{{ scope.row.areaName == null || scope.row.areaName == '' ? '—' :
                scope.row.areaName.length > 7 ?
                  "..." + scope.row.areaName.substring(scope.row.areaName.length - 7,
                    scope.row.areaName.length) : scope.row.areaName }}</span>
            </el-tooltip>
          </template>
</el-table-column> -->

        <el-table-column label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <div class="textBtn">
              <el-row>
                <el-col class="el" :span="8">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                    @click="detailClick(scope.row)">详情</span>
                </el-col>
                <el-col class="el" :span="8">
                  <span style="color: red;cursor: pointer;font-weight: 600;" @click="deleteClick(scope.row)">删除</span>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页器 -->
    <myPagination :total="total" :pageNum="pageNum" @PageChange="PageChange" @pageSizeChange="pageSizeChange">
    </myPagination>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      keywords: '',
      keyResidentialId: '',
      keyResidentialData: [],
      pageNum: 1,
      pageSize: 10,
      total: 6,
      logOnUser: {},
      tableData: [], //表格数据
      activeArr: [],
    }
  },
  activated() {
    this.activeArr = []
    this.cancelArr = []
    this.logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))
    this.getkeyResidentialData()
    this.reset()

  },
  methods: {
    async getkeyResidentialData() {
      let res = await this.$api.patrol.myPatrolGetCommunityList('')
      if (res.code == 200) {
        this.keyResidentialData = res.data
        console.log(this.keyResidentialData, 'this.keyResidentialData');
      } else {
        this.$message.error(res.message)
      }
    },
    dow(row) {
      console.log(row, '下载的所在行')
      axios({
        method: 'get',
        url: defaultUrl + `/business/patrolQRCode/downloadImage?id=${row.id}`,
        headers: {
          // 在这里添加自己需要的请求头
          account: this.logOnUser.account,
          token: this.logOnUser.token,
        },
        responseType: 'blob'
      }).then(res => {
        const url = window.URL.createObjectURL(new Blob([res.data]))
        const a = document.createElement('a')
        a.href = url

        a.setAttribute('download', row.codeImageTotalPath)
        document.body.appendChild(a)
        a.click();
        document.body.removeChild(a)


      }).catch(err => {
      }
      )
    },
    detailClick(row) {
      this.$router.push('/PatrolQRcodeDetail?id=' + row.id)
    },
    deleteClick(row) {
      this.$confirm('是否删除选中的数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {

        let res = await this.$api.patrol.myPatrolQRCodeBatchDeleteCode({
          ids: JSON.stringify([row.id])
        })
        if (res.code == 200) {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getTableList()
        } else {
          this.$message.error(res.message)
        }
      }).catch(() => {

      });
    },
    //  总表格列表=====================================================
    exportCode() {
      if (this.activeArr.length == 0) {
        this.$message.error('请先选择数据')
        return
      }
      axios({
        method: 'post',
        url: defaultUrl + `/business/patrolQRCode/exportCodeZip`,
        data: {
          ids: JSON.stringify(this.activeArr)
        },
        headers: {
          // 在这里添加自己需要的请求头
          account: this.logOnUser.account,
          token: this.logOnUser.token,
        },
        responseType: 'blob'
      }).then(res => {
        const url = window.URL.createObjectURL(new Blob([res.data]))
        const a = document.createElement('a')
        a.href = url
        a.setAttribute('download', '巡查码.zip')
        document.body.appendChild(a)
        a.click();
        document.body.removeChild(a)
      }).catch(err => {
        console.log(err, 'qdqwd');
      }
      )
    },
    batchDelete() {
      console.log(this.activeArr);
      this.$confirm('是否批量删除选中的数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {

        let res = await this.$api.patrol.myPatrolQRCodeBatchDeleteCode({
          ids: JSON.stringify(this.activeArr)
        })
        if (res.code == 200) {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getTableList()
          this.activeArr = []
        } else {
          this.$message.error(res.message)
        }
      }).catch(() => {

      });

    },
    selectTable(selection, row) {
      console.log(selection, row, '单选');
      let haveRow = false
      selection.forEach(el => {
        if (el.id == row.id) {
          haveRow = true
        }
      })
      if (haveRow) {  //新增
        this.activeArr.push(row.id)
      } else {        //去除
        this.activeArr.forEach((el, i) => {
          if (el == row.id) {
            this.activeArr.splice(i, 1)
          }
        })
      }

    },
    async selectAllTable(selection) {
      if (selection.length > 0) { //全部选中
        let res = await this.$api.patrol.myPatrolQRCodeGetSelectIdsArray({
          "keywords": this.keywords, //巡查码名称or类别名称or扫码权限人名 模糊匹配
          "residentialId": this.keyResidentialId //小区id
        })
        if (res.code == 200) {
          this.activeArr = res.data
        } else {
          this.$message.error(res.message)
        }
      } else { //全部取消
        this.activeArr = []
      }
    },
    pageSizeChange(e) {
      this.pageNum = 1
      this.pageSize = e
      this.getTableList()
    },
    PageChange(e) {

      this.pageNum = e
      this.getTableList()
    },
    SouSuo() {
      this.pageNum = 1
      this.getTableList()
    },
    reset() {
      this.keywords = ''
      this.keyResidentialId = ''
      this.pageNum = 1
      this.SouSuo()
    },
    async getTableList() {

      let res = await this.$api.patrol.myGetCodeList({
        "keywords": this.keywords, //巡查码名称or类别名称or扫码权限人名 模糊匹配
        "residentialId": this.keyResidentialId, //小区id
        "pageNum": this.pageNum,
        "pageSize": this.pageSize
      })
      console.log(res, '巡查码列表');


      if (res.code == 200) {
        if (res.data.list.length == 0 && this.pageNum != 1) {
          this.pageNum = 1
          this.getTableList()
          return
        }
        this.tableData = res.data.list;
        this.total = res.data.total;

        //  回显表格选中的元素
        if (this.activeArr.length > 0) {
          this.tableData.forEach((el, i) => {
            this.activeArr.forEach((ell, ii) => {
              if (el.id == ell) {
                this.$nextTick(() => {
                  this.$refs.table.toggleRowSelection(this.tableData[i], true)
                })
              }
            });
          })
        }
      } else {
        this.$message.error(res.message)
      }

    },
    // =====================================================总表格列表
  }
}
</script>

<style lang="less" scoped>
.textBtn {
  position: relative;

  /deep/ .el-row {
    display: flex;
    justify-content: center;
  }

  .el {
    display: block;
    position: relative;

    &:nth-child(n+2) {
      &::after {
        position: absolute;
        left: -1px;
        top: 50%;
        content: '';
        width: 2px;
        transform: translateY(-50%) scale(0.5, 1);
        height: 10px;
        background-color: #aaa;
      }
    }
  }
}
</style>